package com.draven.config;

import com.draven.common.BusinessException;
import com.draven.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("${jwt.header}")
    private String header;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果不是映射到方法，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取请求头中的token
        String authHeader = request.getHeader(header);
        if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(tokenHead)) {
            throw new BusinessException(401, "请先登录");
        }

        // 截取token
        String token = authHeader.substring(tokenHead.length()).trim();

        try {
            // 验证token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                throw new BusinessException(401, "登录已过期，请重新登录");
            }

            // 获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            // 将用户ID存入request中
            request.setAttribute("userId", userId);
            
            // 获取用户名
            String username = jwtUtil.getUsernameFromToken(token);
            // 将用户名存入request中
            request.setAttribute("username", username);

            return true;
        } catch (Exception e) {
            log.error("Token验证失败", e);
            throw new BusinessException(401, "登录已过期，请重新登录");
        }
    }
}